import constant from "./constant.js";
import ToolApis from "@/api/api.js";
import { store } from "@/stores/index.js";
import toolAction from "@/tool/http/tool-action.js";
import tool from "@/tool/tool.js";

async function init(code, dsId) {
  let config = {};
  config.api = toolAction.init(code);
  let metadata = await config.api.meta();
  try {
    let res = await import(
      `./rules/${code}/${dsId || store.app.dsId || ""}rule.js`
    );
    config = await res.default(metadata);
  } catch (e) {
    console.warn(e);
  }

  config.extendField = config.extendField || "extend_json";
  config.baseField = config.baseField || [];
  config.extendFields = config.extendFields || [];
  config.extendArrays = config.extendArrays || [];
  config.listFieldExtend = config.listFieldExtend || (async () => {});
  config.metadata = config.metadata || [];

  // metaMerge(await config.api.meta(), config.metaConfig);
  metaMergeNew(config.metadata, metadata);
  await metaBuild(config.metadata, dsId);
  return config;
}

export default {
  init,
};

async function metaMergeNew(metaConfig, metadata) {
  metadata.forEach((meta) => {
    let nMeta = metaConfig.find((item) => item.name === meta.name);
    if (nMeta) {
      tool.objAssignOfNull(nMeta, meta);
      // Object.assign(nMeta, meta);
    } else {
      metaConfig.push((nMeta = meta));
    }
    if (nMeta.dictList === null) {
      delete nMeta.dictList;
    }
  });
}

async function metaBuild(metadata, dsId) {
  for (let i = 0; i < metadata.length; i++) {
    let meta = metadata[i];
    if (!meta.dictList && constant[meta.type]) {
      meta.dictList = constant[meta.type];
    }
    if (!dsId) {
      if (meta.name === "tenant_id") {
        meta.dictList = await ToolApis.dictTenant();
      }
    }
    meta.hiddenFun = meta.hiddenFun || (() => false);
  }
}

function metaMerge(metadata, config) {
  if (!config) return;
  let tempConfig = config;
  let keys = [];
  metadata.forEach((meta) => {
    let metaConfig = tempConfig[meta.name];
    if (metaConfig) {
      if (metaConfig.dictList === null) {
        delete metaConfig.dictList;
      }
      Object.assign(meta, metaConfig);
      keys.push(meta.name);
    }
  });
  Object.keys(tempConfig)
    .filter((item) => !keys.includes(item))
    .forEach((key) => {
      metadata.push(tempConfig[key]);
    });
}
